package eproject.mm.com.projectsupervision.activity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Icon;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import org.w3c.dom.Text;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import eproject.mm.com.projectsupervision.PrjApplication;
import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.receiver.LocalServiceReceiver;
import eproject.mm.com.projectsupervision.service.JobHandlerService;
import eproject.mm.com.projectsupervision.util.HttpUtil;
import eproject.mm.com.projectsupervision.util.LocationUtil;
import eproject.mm.com.projectsupervision.util.TimeUtil;
import eproject.mm.com.projectsupervision.widget.CustomDatePicker;
import eproject.mm.com.projectsupervision.widget.IconFontTextview;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class CardActivity extends Activity {
    IconFontTextview  iftv_back;
    TextView tv_time;
    CustomDatePicker customDatePicker;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);

    LoadingDialog loadingDialog = null;

    TextView tv_doCard_time_AM,tv_doCard_address_AM;
    LinearLayout ll_address_AM;

    TextView tv_doCard_time_PM,tv_doCard_address_PM;
    LinearLayout ll_address_PM;

    RelativeLayout rl_card_AM, rl_card_PM;
    private OkHttpClient client;

    public LocationClient mLocationClient = null;
    String cardType;

    SharedPreferences userSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card);

        userSettings = getApplication().getSharedPreferences("setting", Context.MODE_MULTI_PROCESS);

        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());

        iftv_back = (IconFontTextview)findViewById(R.id.iftv_back);
        tv_time = (TextView)findViewById(R.id.tv_time);

        tv_doCard_time_AM = (TextView)findViewById(R.id.tv_doCard_time_AM);
        tv_doCard_address_AM = (TextView)findViewById(R.id.tv_doCard_address_AM);
        tv_doCard_time_PM = (TextView)findViewById(R.id.tv_doCard_time_PM);
        tv_doCard_address_PM = (TextView)findViewById(R.id.tv_doCard_address_PM);

        ll_address_AM = (LinearLayout) findViewById(R.id.ll_address_AM);
        rl_card_AM = (RelativeLayout)findViewById(R.id.rl_card_AM);
        ll_address_PM = (LinearLayout)findViewById(R.id.ll_address_PM);
        rl_card_PM = (RelativeLayout)findViewById(R.id.rl_card_PM);

        client = new OkHttpClient.Builder()
                .connectTimeout(300, TimeUnit.SECONDS)
                .readTimeout(1000, TimeUnit.SECONDS)
                .build();

        initDatePicker();

        initEvent();

        hideAll();

        String now = sdf.format(new Date());
        loadData(now.split(" ")[0]);
    }
    private void hideAll(){
        tv_doCard_time_AM.setVisibility(View.GONE);
        tv_doCard_time_PM.setVisibility(View.GONE);

        ll_address_AM.setVisibility(View.GONE);
        ll_address_PM.setVisibility(View.GONE);

        rl_card_AM.setVisibility(View.GONE);
        rl_card_PM.setVisibility(View.GONE);
    }
    public void initEvent(){
        iftv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customDatePicker.show(tv_time.getText().toString());
            }
        });

        rl_card_AM.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cardType = "0";
                doCard();
            }
        });
        rl_card_PM.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cardType = "1";
                doCard();
            }
        });
    }

    private void initDatePicker() {
        String now = sdf.format(new Date());
        tv_time.setText(now.split(" ")[0]);

        customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tv_time.setText(time.split(" ")[0]);
                loadData(tv_time.getText().toString().trim());
            }
        }, "2010-01-01 00:00", "2020-12-31 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(false); // 不显示时和分
        customDatePicker.setIsLoop(false); // 不允许循环滚动
    }

    private void loadData(final String date){
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("加载中...").show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String projectStr = HttpUtil.get("/getDayCardRecord?carddate="+date);

                    handler.sendMessage(handler.obtainMessage(1, projectStr));
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(CardActivity.this,e.toString(),Toast.LENGTH_LONG);
                    handler.sendMessage(handler.obtainMessage(2, null));
                }
            }
        }).start();
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String str = (String)msg.obj;
                    Gson gson=new Gson();
                    Map resultMap = gson.fromJson(str, Map.class);
                    if (resultMap != null && (boolean) resultMap.get("success")) {
                        Map amMap = (Map) resultMap.get("am");
                        Map pmMap = (Map) resultMap.get("pm");

                        loadingDialog.close();

                        String now = sdf.format(new Date());
                        String curDate = now.split(" ")[0];

                        if(amMap == null){
                            tv_doCard_time_AM.setVisibility(View.GONE);
                            ll_address_AM.setVisibility(View.GONE);

                            if(curDate.equals(tv_time.getText().toString())) {
                                rl_card_AM.setVisibility(View.VISIBLE);
                            }else{
                                rl_card_AM.setVisibility(View.GONE);
                            }

                            tv_doCard_time_PM.setVisibility(View.GONE);
                            ll_address_PM.setVisibility(View.GONE);
                            rl_card_PM.setVisibility(View.GONE);
                        }else{
                            tv_doCard_time_AM.setText("打卡时间:"+(String)amMap.get("CREATETIME"));
                            tv_doCard_time_AM.setVisibility(View.VISIBLE);
                            tv_doCard_address_AM.setText((String)amMap.get("ADDRESS"));
                            ll_address_AM.setVisibility(View.VISIBLE);
                            rl_card_AM.setVisibility(View.GONE);

                            if(pmMap == null){
                                tv_doCard_time_PM.setVisibility(View.GONE);
                                ll_address_PM.setVisibility(View.GONE);

                                if(curDate.equals(tv_time.getText().toString())) {
                                    rl_card_PM.setVisibility(View.VISIBLE);
                                }else{
                                    rl_card_PM.setVisibility(View.GONE);
                                }
                            }else{
                                tv_doCard_time_PM.setText("打卡时间:"+(String)pmMap.get("CREATETIME"));
                                tv_doCard_time_PM.setVisibility(View.VISIBLE);
                                tv_doCard_address_PM.setText((String)pmMap.get("ADDRESS"));
                                ll_address_PM.setVisibility(View.VISIBLE);
                                rl_card_PM.setVisibility(View.GONE);
                            }
                        }

                    }
                    break;
                case 2:
                    loadingDialog.close();
                    break;
                case 10:
                    Map mAM = (Map)msg.obj;

                    tv_doCard_time_AM.setVisibility(View.VISIBLE);
                    ll_address_AM.setVisibility(View.VISIBLE);
                    rl_card_AM.setVisibility(View.GONE);

                    tv_doCard_time_AM.setText("打卡时间:" + sdf.format(new Date()));
                    tv_doCard_address_AM.setText((String)mAM.get("address"));

                    Intent intentOn =  new Intent();
                    intentOn.putExtra("cardType", "0");//上班
                    setResult(101, intentOn);

                    final SharedPreferences.Editor editorOn = userSettings.edit();
                    editorOn.putString("workdate", TimeUtil.getCurrDate());
                    editorOn.putString("workstatus", "1");
                    editorOn.putInt("stepCount", 0);

                    editorOn.commit();

                    if(!PrjApplication.getInstance().isServiceStarted()){
                        PrjApplication.getInstance().StartLocalService(1);
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                            Intent intent = new Intent();
//                            intent.setClass(CardActivity.this, JobHandlerService.class);
//                            startService(intent);
//                        } else {
//                            PrjApplication.getInstance().StartLocalService(1);
//                        }
                    }

                    //启动定时间器
//                    Intent intentStart = new Intent();
//                    intentStart.setAction("android.intent.action.MY_SERVICESTART_BROADCAST");
//                    PendingIntent pendingIntentStart = PendingIntent.getBroadcast(getApplicationContext(), 0, intentStart, PendingIntent.FLAG_UPDATE_CURRENT);
//                    AlarmManager alarmManagerStart = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
//
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.setTimeInMillis(System.currentTimeMillis());
//                    calendar.add(Calendar.SECOND, 0);
//
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                        //参数2是开始时间、参数3是允许系统延迟的时间
//                        alarmManagerStart.setExact(AlarmManager.RTC_WAKEUP , calendar.getTimeInMillis(), pendingIntentStart);
//                    } else {
//                        alarmManagerStart.set(AlarmManager.RTC_WAKEUP , calendar.getTimeInMillis() , pendingIntentStart);
//                    }

                    break;
                case 11:
                    Map mPM = (Map)msg.obj;

                    tv_doCard_time_PM.setVisibility(View.VISIBLE);
                    ll_address_PM.setVisibility(View.VISIBLE);
                    rl_card_PM.setVisibility(View.GONE);

                    tv_doCard_time_PM.setText("打卡时间:" + sdf.format(new Date()));
                    tv_doCard_address_PM.setText((String)mPM.get("address"));

                    Intent intentOff =  new Intent();
                    intentOff.putExtra("cardType", "1");//下班
                    setResult(102, intentOff);

                    final SharedPreferences.Editor editorOff = userSettings.edit();
                    editorOff.putString("workstatus", "0");
                    editorOff.commit();

                    if(PrjApplication.getInstance().isServiceStarted()){
                        PrjApplication.getInstance().StopLocalService();
                    }
//                    //关闭定时间器
//                    Intent intentStop = new Intent(getApplicationContext(),LocalServiceReceiver.class);
//                    intentStop.setAction("android.intent.action.MY_SERVICESTOP_BROADCAST");
//                    PendingIntent pendingIntentStop = PendingIntent.getBroadcast(getApplicationContext(), 0, intentStop, PendingIntent.FLAG_UPDATE_CURRENT);
//                    AlarmManager alarmManagerStop = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
//                    alarmManagerStop.cancel(pendingIntentStop);

                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };

    private void doCard(){
        LocationClientOption mOption = new LocationClientOption();

        mOption.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        mOption.setIsNeedAddress(false);//可选，设置是否需要地址信息，默认不需要
        mOption.setIsNeedLocationDescribe(true);//可选，设置是否需要地址描述
        mOption.setNeedDeviceDirect(false);//可选，设置是否需要设备方向结果
        mOption.setLocationNotify(false);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        mOption.setIgnoreKillProcess(true);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        mOption.setIsNeedLocationDescribe(false);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        mOption.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        mOption.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        mOption.setOpenGps(true);//可选，默认false，设置是否开启Gps定位
        mOption.setIsNeedAltitude(false);//可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        mLocationClient.setLocOption(mOption);

        mLocationClient.start();

        if(1==1)return;
        Location location = LocationUtil.getLocation(CardActivity.this);
        if(location==null){
            Toast.makeText(CardActivity.this,"获取定位信息失败,请开启GPS定位",Toast.LENGTH_SHORT).show();
        }else{
            //Toast.makeText(getActivity(),"经度：" + location.getLongitude() + ", 纬度："
            //        + location.getLatitude(),Toast.LENGTH_SHORT).show();

        }
    }
    String respStr = "";
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location){
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取位置描述信息相关的结果
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            final String locationDescribe = location.getLocationDescribe();    //获取位置描述信息
            final String lng = location.getLongitude()+"";
            final String lat = location.getLatitude()+"";

            final LoadingDialog loadingDialog = new LoadingDialog(CardActivity.this);
            loadingDialog.setLoadingText("加载中...").show();


            new Thread(new Runnable() {
                @Override
                public void run() {
//                    try {
//                        String projectStr = HttpUtil.get("/getDayCardRecord?carddate="+date);
//
//                        handler.sendMessage(handler.obtainMessage(1, projectStr));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        Toast.makeText(CardActivity.this,e.toString(),Toast.LENGTH_LONG);
//                        handler.sendMessage(handler.obtainMessage(2, null));
//                    }
                    try {
                        int stepCount = userSettings.getInt("stepCount",0);

                        okhttp3.FormBody.Builder builder = new okhttp3.FormBody.Builder();
                        builder.add("type",cardType);
                        builder.add("x",lng);
                        builder.add("y",lat);
                        builder.add("address",locationDescribe==null?"":locationDescribe);
                        builder.add("carddate",tv_time.getText().toString());

                        if(cardType.equals("1")) {
                            builder.add("stepcount",stepCount+"");
                        }

                        RequestBody requestBody = builder.build();
                        Request.Builder okbuilder = new Request.Builder();
                        okbuilder.addHeader("authenticationToken", PrjApplication.getInstance().getAuthenticationToken());
                        Request requestPostCard = okbuilder
                                .url("http://"+ PrjApplication.getInstance().getServerIp() +":"+PrjApplication.getInstance().getServerPort()+"/"+PrjApplication.getInstance().getPreFixPath()+"/saveCardRecord")
                                .post(requestBody)
                                .build();
                        client.newCall(requestPostCard).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                loadingDialog.close();
                            }

                            @Override
                            public void onResponse(Call call, final Response res) throws IOException {
                                respStr = "{}";
                                try{
                                    respStr = res.body().string();
                                }catch (Exception ioe){
                                    respStr = "{success:false,message:'http error'}";
                                }
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        loadingDialog.close();
//                                        String str = "{}";
//                                        try{
//                                            str = res.body().string();
//                                        }catch (Exception ioe){
//                                            str = "{success:false,message:'http error'}";
//                                        }
                                        Gson gson=new Gson();
                                        Map resultMap = gson.fromJson(respStr, Map.class);
                                        if (resultMap != null && (boolean) resultMap.get("success")) {
                                            resultMap.put("address",locationDescribe);
                                            if(cardType.equals("0")) {
                                                Toast.makeText(CardActivity.this,"上班",Toast.LENGTH_SHORT).show();
                                                handler.sendMessage(handler.obtainMessage(10, resultMap));
                                            }else{
                                                Toast.makeText(CardActivity.this,"下班",Toast.LENGTH_SHORT).show();
                                                handler.sendMessage(handler.obtainMessage(11, resultMap));
                                            }
                                        }else{
                                            String message = (String)resultMap.get("message");
                                            Toast.makeText(CardActivity.this,message,Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }
                        });
                    }catch (Exception e){
                        loadingDialog.close();
                    }
                }
            }).start();
        }
    }
}
